package com.yxy.framework.security.handle;

import java.io.IOException;
import java.util.Map;
import java.util.TimerTask;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.alibaba.fastjson2.JSON;
import com.yxy.common.constant.Constants;
import com.yxy.common.core.domain.AjaxResult;
import com.yxy.common.core.domain.model.LoginUser;
import com.yxy.common.utils.MessageUtils;
import com.yxy.common.utils.ServletUtils;
import com.yxy.common.utils.StringUtils;
import com.yxy.framework.manager.AsyncManager;
import com.yxy.framework.manager.factory.AsyncFactory;
import com.yxy.framework.web.service.TokenService;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author ruoyi
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{  private static final Logger log = LoggerFactory.getLogger(LogoutSuccessHandlerImpl.class);
    @Autowired
    private TokenService tokenService;

    @Value("${sso.url}")
    private   String ssoUrl;

    @Value("${sso.client_id}")
    private   String client_id;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            String userName = loginUser.getUsername();
            String localToken = tokenService.getToken(request);
            if (localToken == null) {
                localToken = request.getParameter(Constants.TOKEN);
            }
            log.info("onLogoutSuccess.localToken:{}", localToken);
            // 2. 从Redis获取关联的SSO access_token
            String josnData = redisTemplate.opsForValue().get(
                    "user_token:" + loginUser.getUserId()
            );
            log.info("onLogoutSuccess.ssoAccessToken:{}", josnData);
            // 3. 调用认证中心登出接口（异步）
            if (StrUtil.isNotBlank(josnData)) {
                Map<String, Object> josnMap = JSON.parseObject(josnData);
                String ssoAccessToken= josnMap.get("access_token").toString();
                log.info("onLogoutSuccess.ssoAccessToken:run", ssoAccessToken);
                asyncCallSsoLogout(ssoAccessToken);
                redisTemplate.delete("user_token:" + loginUser.getUserId());
            }
            // 4. 清理本地会话
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
    }

    /**
     * 异步调用认证中心登出接口
     */
    private void asyncCallSsoLogout(String accessToken) {
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    headers.set("Authorization", "Bearer " + accessToken);
                    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

                    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
                    params.add("client_id", client_id);

                    new RestTemplate().postForObject(
                            ssoUrl + "/oauth2/logout",
                            new HttpEntity<>(params, headers),
                            String.class
                    );
                    log.info("认证中心登出成功");
                } catch (Exception e) {
                    log.error("认证中心登出失败", e);
                }
            }
        });
    }
}
